<template>
  <n-modal
    v-model:show="visible"
    :mask-closable="false"
    :close-on-esc="true"
    preset="card"
    :style="modalStyle"
    :content-style="contentStyle"
    :header-style="headerStyle"
    size="huge"
    :bordered="false"
    @update:show="handleClose"
  >
    <template #header>
      <div class="modal-header">
        <span class="modal-title">表格对比结果</span>
        <div class="header-legend">
          <n-space :size="16">
            <div class="legend-item">
              <div class="legend-color same"></div>
              <span>相同</span>
            </div>
            <div class="legend-item">
              <div class="legend-color modified"></div>
              <span>修改</span>
            </div>
            <div class="legend-item">
              <div class="legend-color added"></div>
              <span>新增</span>
            </div>
            <div class="legend-item">
              <div class="legend-color deleted"></div>
              <span>删除</span>
            </div>
            <div class="legend-item">
              <div class="legend-color hover"></div>
              <span>悬停</span>
            </div>
          </n-space>
        </div>
      </div>
    </template>
    
    <template #header-extra>
      <n-space>
        <n-button
          v-if="result"
          type="primary"
          size="small"
          @click="handleDownload"
        >
          下载报告
        </n-button>
        <n-button
          size="small"
          @click="handleClose"
        >
          关闭
        </n-button>
      </n-space>
    </template>

    <div v-if="loading" class="loading-container">
      <n-spin size="large" />
      <n-text>正在对比表格...</n-text>
    </div>

    <div v-else-if="result" class="comparison-content">
      <!-- 对比摘要 -->
      <n-card title="对比摘要" :bordered="false" class="summary-card">
        <n-grid :cols="24" :x-gap="16" :y-gap="16">
          <n-gi :span="isMobile ? 24 : 8">
            <n-statistic label="相同行数" :value="result.summary.comparison.sameRows" />
          </n-gi>
          <n-gi :span="isMobile ? 24 : 8">
            <n-statistic label="修改行数" :value="result.summary.comparison.modifiedRows" />
          </n-gi>
          <n-gi :span="isMobile ? 24 : 8">
            <n-statistic label="新增行数" :value="result.summary.comparison.addedRows" />
          </n-gi>
        </n-grid>
      </n-card>

      <!-- 左右对比视图 -->
      <div class="comparison-view">
        <div class="table-header">
          <div class="table-title left">
            <n-icon size="20" color="#18a058">
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
                <path d="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M18,20H6V4H13V9H18V20Z"/>
              </svg>
            </n-icon>
            <span>{{ result.summary.table1.fileName }}</span>
          </div>
          <div class="vs-divider">VS</div>
          <div class="table-title right">
            <n-icon size="20" color="#d03050">
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
                <path d="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M18,20H6V4H13V9H18V20Z"/>
              </svg>
            </n-icon>
            <span>{{ result.summary.table2.fileName }}</span>
          </div>
        </div>

        <!-- 同步滚动的表格容器 -->
        <div class="tables-container" ref="tablesContainer">
          <div class="table-wrapper left" ref="leftTable" @scroll="handleLeftScroll">
            <table class="comparison-table">
              <thead>
                <tr>
                  <th class="row-number-header">行号</th>
                  <th v-for="(col, index) in result.details.columns" :key="index">
                    {{ col.table1Name }}
                  </th>
                </tr>
              </thead>
              <tbody>
                <tr
                  v-for="row in result.details.rows"
                  :key="row.rowNumber"
                  :class="getRowClass(row.status)"
                >
                  <td class="row-number">{{ row.rowNumber }}</td>
                  <td
                    v-for="(value, index) in row.table1Data"
                    :key="index"
                    :class="getCellClass(row, index, 'table1')"
                    @mouseenter="handleCellMouseEnter(row.rowNumber, index)"
                    @mouseleave="handleCellMouseLeave"
                  >
                    {{ value || '-' }}
                  </td>
                </tr>
              </tbody>
            </table>
          </div>

          <div class="table-wrapper right" ref="rightTable" @scroll="handleRightScroll">
            <table class="comparison-table">
              <thead>
                <tr>
                  <th class="row-number-header">行号</th>
                  <th v-for="(col, index) in result.details.columns" :key="index">
                    {{ col.table2Name }}
                  </th>
                </tr>
              </thead>
              <tbody>
                <tr
                  v-for="row in result.details.rows"
                  :key="row.rowNumber"
                  :class="getRowClass(row.status)"
                >
                  <td class="row-number">{{ row.rowNumber }}</td>
                  <td
                    v-for="(value, index) in row.table2Data"
                    :key="index"
                    :class="getCellClass(row, index, 'table2')"
                    @mouseenter="handleCellMouseEnter(row.rowNumber, index)"
                    @mouseleave="handleCellMouseLeave"
                  >
                    {{ value || '-' }}
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </n-modal>
</template>

<script setup lang="ts">
import { ref, computed, nextTick, watch } from 'vue'
import { useMessage } from 'naive-ui'
import type { ComparisonResult } from '@/api/utility/tableComparison'
import { useBreakpoint } from '@/utils/responsive-helper'

interface Props {
  modelValue: boolean
  result: ComparisonResult | null
  loading?: boolean
}

const props = defineProps<Props>()
const emit = defineEmits(['update:modelValue', 'download'])

const { isMobile } = useBreakpoint()
const message = useMessage()

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 样式计算
const modalStyle = computed(() => ({
  position: 'fixed',
  top: '60px', // 顶部菜单高度
  left: '0',
  right: '0',
  bottom: '0',
  margin: '0',
  maxHeight: 'calc(100vh - 60px)',
  height: 'calc(100vh - 60px)',
  display: 'flex',
  flexDirection: 'column'
}))

const contentStyle = computed(() => ({
  height: '100%',
  display: 'flex',
  flexDirection: 'column',
  padding: isMobile.value ? '12px' : '20px'
}))

const headerStyle = computed(() => ({
  padding: isMobile.value ? '12px' : '16px 20px'
}))

// 表格滚动相关
const leftTable = ref<HTMLElement>()
const rightTable = ref<HTMLElement>()
let isScrolling = false

// 单元格高亮相关
const hoveredCell = ref<{ row: number; col: number } | null>(null)

const handleLeftScroll = (e: Event) => {
  if (isScrolling || !rightTable.value) return
  isScrolling = true
  const target = e.target as HTMLElement
  rightTable.value.scrollTop = target.scrollTop
  rightTable.value.scrollLeft = target.scrollLeft
  setTimeout(() => { isScrolling = false }, 10)
}

const handleRightScroll = (e: Event) => {
  if (isScrolling || !leftTable.value) return
  isScrolling = true
  const target = e.target as HTMLElement
  leftTable.value.scrollTop = target.scrollTop
  leftTable.value.scrollLeft = target.scrollLeft
  setTimeout(() => { isScrolling = false }, 10)
}

// 获取行的样式类
const getRowClass = (status: string) => {
  return {
    'row-same': status === 'SAME',
    'row-modified': status === 'MODIFIED',
    'row-added': status === 'ADDED',
    'row-deleted': status === 'DELETED'
  }
}

// 获取单元格的样式类
const getCellClass = (row: any, colIndex: number, table: 'table1' | 'table2') => {
  const classes: string[] = []
  
  // 差异样式
  if (row.status === 'MODIFIED' && row.differences) {
    const hasDiff = row.differences.some((diff: any) => diff.columnIndex === colIndex)
    if (hasDiff) classes.push('cell-different')
  }
  
  // 悬停样式
  if (hoveredCell.value && 
      hoveredCell.value.row === row.rowNumber && 
      hoveredCell.value.col === colIndex) {
    classes.push('cell-hovered')
  }
  
  return classes.join(' ')
}

// 处理单元格鼠标事件
const handleCellMouseEnter = (rowNumber: number, colIndex: number) => {
  hoveredCell.value = { row: rowNumber, col: colIndex }
}

const handleCellMouseLeave = () => {
  hoveredCell.value = null
}

const handleClose = () => {
  visible.value = false
}

const handleDownload = () => {
  emit('download')
}

// 监听显示状态，重置滚动位置
watch(visible, (newVal) => {
  if (newVal) {
    nextTick(() => {
      if (leftTable.value) leftTable.value.scrollTop = 0
      if (rightTable.value) rightTable.value.scrollTop = 0
    })
  }
})
</script>

<style scoped lang="less">
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400px;
  gap: 16px;
}

.comparison-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.summary-card {
  flex-shrink: 0;
}

.comparison-view {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.table-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 0;
  border-bottom: 1px solid var(--n-border-color);
  flex-shrink: 0;
  
  .table-title {
    flex: 1;
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 500;
    
    &.left {
      justify-content: flex-start;
    }
    
    &.right {
      justify-content: flex-end;
    }
  }
  
  .vs-divider {
    padding: 0 20px;
    font-weight: bold;
    color: var(--n-text-color3);
  }
}

.tables-container {
  flex: 1;
  display: flex;
  gap: 2px;
  min-height: 0;
  margin-top: 16px;
  background: var(--n-border-color);
}

.table-wrapper {
  flex: 1;
  overflow: auto;
  background: var(--n-color);
  
  &.left {
    border-right: 1px solid var(--n-border-color);
  }
}

.comparison-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
  
  th, td {
    padding: 8px 12px;
    text-align: left;
    border-bottom: 1px solid var(--n-border-color);
    white-space: nowrap;
  }
  
  th {
    background: var(--n-color-modal);
    font-weight: 500;
    position: sticky;
    top: 0;
    z-index: 10;
  }
  
  .row-number-header,
  .row-number {
    width: 60px;
    text-align: center;
    background: var(--n-color-modal);
    position: sticky;
    left: 0;
    z-index: 5;
  }
  
  .row-number-header {
    z-index: 11;
  }
  
  // 行状态样式
  .row-same {
    background: transparent;
  }
  
  .row-modified {
    background: rgba(250, 173, 20, 0.1);
  }
  
  .row-added {
    background: rgba(82, 196, 26, 0.1);
  }
  
  .row-deleted {
    background: rgba(245, 34, 45, 0.1);
  }
  
  // 单元格差异样式
  .cell-different {
    background: rgba(250, 173, 20, 0.2);
    font-weight: 500;
  }
  
  // 单元格悬停样式
  td {
    position: relative;
    transition: all 0.2s ease;
    cursor: pointer;
    
    &.cell-hovered {
      background: rgba(24, 160, 88, 0.15) !important;
      outline: 2px solid rgba(24, 160, 88, 0.5);
      outline-offset: -1px;
      z-index: 2;
      
      // 差异单元格悬停时
      &.cell-different {
        background: rgba(250, 173, 20, 0.35) !important;
        outline-color: rgba(250, 173, 20, 0.8);
      }
    }
  }
}

// 模态框头部样式
.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  
  .modal-title {
    font-size: 18px;
    font-weight: 500;
  }
  
  .header-legend {
    display: flex;
    align-items: center;
    gap: 16px;
    margin-left: auto;
    margin-right: 20px;
  }
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  
  .legend-color {
    width: 14px;
    height: 14px;
    border-radius: 3px;
    
    &.same {
      background: transparent;
      border: 1px solid var(--n-border-color);
    }
    
    &.modified {
      background: rgba(250, 173, 20, 0.3);
      border: 1px solid rgba(250, 173, 20, 0.5);
    }
    
    &.added {
      background: rgba(82, 196, 26, 0.3);
      border: 1px solid rgba(82, 196, 26, 0.5);
    }
    
    &.deleted {
      background: rgba(245, 34, 45, 0.3);
      border: 1px solid rgba(245, 34, 45, 0.5);
    }
    
    &.hover {
      background: rgba(24, 160, 88, 0.2);
      border: 2px solid rgba(24, 160, 88, 0.5);
    }
  }
}

// 移动端适配
@media (max-width: 768px) {
  .modal-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
    
    .header-legend {
      margin-left: 0;
      margin-right: 0;
      width: 100%;
      overflow-x: auto;
      
      .n-space {
        flex-wrap: nowrap;
      }
    }
  }
  
  .legend-item {
    font-size: 12px;
    white-space: nowrap;
  }
  
  .table-header {
    flex-direction: column;
    gap: 8px;
    
    .table-title {
      justify-content: center !important;
    }
    
    .vs-divider {
      display: none;
    }
  }
  
  .tables-container {
    flex-direction: column;
  }
  
  .table-wrapper {
    &.left {
      border-right: none;
      border-bottom: 2px solid var(--n-border-color);
    }
  }
  
  .comparison-table {
    font-size: 12px;
    
    th, td {
      padding: 6px 8px;
    }
  }
}

// 滚动条样式
.table-wrapper {
  &::-webkit-scrollbar {
    width: 8px;
    height: 8px;
  }
  
  &::-webkit-scrollbar-track {
    background: var(--n-color-modal);
  }
  
  &::-webkit-scrollbar-thumb {
    background: var(--n-scrollbar-color);
    border-radius: 4px;
  }
  
  &::-webkit-scrollbar-thumb:hover {
    background: var(--n-scrollbar-color-hover);
  }
}
</style>